package com.wf.atm.dao;

import com.wf.atm.pojo.Account;
import com.wf.atm.utils.IOUtils;
import com.wf.atm.utils.MD5Utils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @author mpk
 * @since 2024/6/10 12:21:11
 */
public class FileDao implements FileMapper {

    File file = new File("src/com/wf/atm/account");


    @Override
    public void setId(String id)   {

        IOUtils.writeId(id, "id.txt");

    }

    @Override
    public Long getId()   {
        return IOUtils.readId("id.txt");
    }

    @Override
    public boolean insertAccount(Account account)   {

        IOUtils.writeFile(account, getId() + ".txt");

        return true;
    }

    @Override
    public boolean deleteAccount(Account account) {
        return true;
    }

    @Override
    public Account selectActById(Long id)  {


        File[] files = file.listFiles();

        if (files != null) {
            for (File f : files) {

                if (f.getName().equals(id + ".txt")) {

                    return (Account) IOUtils.readFile(f.getAbsolutePath());
                }

            }
        }

     return  null;


    }

    @Override
    public Account selectActByIdAndPwd(Long id, String pwd)  {

        Account act = selectActById(id);
        if (act!= null) {
            if (MD5Utils.valid(pwd,act.getPassword())) {
                return act;
            }
        }
       return null;


    }

    @Override
    public boolean updateAccount(Account account)  {


        Account act = selectActById(account.getId());
        if (act != null) {
            act = account;
            IOUtils.writeFile(act, act.getId() + ".txt");
            return true;

        }

        return false;
    }


    @Override
    public List<Account> selectAll()  {

        File[] files = file.listFiles();

        ArrayList<Account> accounts = new ArrayList<>();

        if (files != null) {
            for (File f : files) {
                if(f.getName().matches("[0-9]{18}\\.txt")) {
                    Account a = (Account) IOUtils.readFile(f.getAbsolutePath());
                    accounts.add(a);
                }
            }
        }


        return accounts;
    }


}
